package com.karl.mytask_2.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.karl.mytask_2.R;
import com.karl.mytask_2.fragment.UserFragment;

/**
 * Created by Karl on 2016/5/20.
 */
public class UserAdapter extends RecyclerView.Adapter<UserViewHolder> implements View.OnClickListener {
    String[] mListName;
    int[] mListImg;

    public UserAdapter(String[] mListName, int[] mListImg) {
        this.mListName = mListName;
        this.mListImg = mListImg;
    }

    private OnRecyclerViewItemClickListener mOnItemClickListener = null;//第二步

    @Override
    public void onClick(View v) {//第四步
        if (mOnItemClickListener != null) {
            //这里使用getTag方法获取
            mOnItemClickListener.onItemClick(v,(String)v.getTag());
        }
    }
    //暴露给外面的调用者——第六步
    public void setOnItemClickListener(OnRecyclerViewItemClickListener listener){
        this.mOnItemClickListener = listener;
    }

    //定义接口——第一步
    public static interface OnRecyclerViewItemClickListener{
        void onItemClick(View view,String data);
    }


    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_item_list,null);
        UserViewHolder uViewHolder = new UserViewHolder(mView);

        //给创建的View注册点击事件——第三步
        mView.setOnClickListener(this);

        return uViewHolder;
    }

    @Override
    public void onBindViewHolder(UserViewHolder holder, int position) {
        holder.mTxt.setText(mListName[position]);
        holder.mImg.setImageResource(mListImg[position]);

        //将数据保存到itemview的tag中，方便点击时获取——第五步
        holder.itemView.setTag(mListName[position]);
//        //自定义点击事件
//        holder.itemView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });

    }

    @Override
    public int getItemCount() {
        return mListName.length;
    }
}
class UserViewHolder extends RecyclerView.ViewHolder {
    ImageView mImg;
    TextView mTxt;
    public UserViewHolder(View itemView) {
        super(itemView);
        mImg = (ImageView) itemView.findViewById(R.id.user_item_img);
        mTxt = (TextView) itemView.findViewById(R.id.user_item_txt);
    }
}

